import utils from '@/utils'
import { webUrl, communityWebSocketUrl } from '@/api/request'
import { getParamUrl } from '@/utils/commonUtil'
import { delCookie, getCookie } from './cookie'

var MAX = 1000
var count = 0
var t
function getWebIP() {
    var curIP = window.location.hostname
    return curIP
}

function initWebSocket(messageCallBack, opt, url) {
    var cityCountyValue = getParamUrl('cityCountyValue') ? '_' + getParamUrl('cityCountyValue') : '_' + getCookie('districtCode')
    opt = opt + cityCountyValue
    console.log('websocketOpt', opt)
    var websock = new WebSocket(url ? communityWebSocketUrl : webUrl)
    websock.onclose = (e) => {
        websock.close()
        websock = null
    }
    websock.onerror = () => {
        console.log('WebSocket连接发生错误')
    }
    websock.addEventListener('open', () => {
        let obj = {
            type: 'register',
            register_type: 'add',
            listen_type: 'broadcast',
            listen_group:opt,
            aa: opt
        }
        // this.websocketSend(obj)
        websock.send(JSON.stringify(obj))
        console.log('---websocketOpen----')
    })
    websock.onmessage = (e) => {
        if (messageCallBack) {
            messageCallBack(e, opt)
        }
    }
    return websock
}

// 实际调用的方法
function sendSock(agentData, callback) {
    if (websock.readyState === websock.OPEN) {
        // 若是ws开启状态
        websocketsend(agentData)
    } else if (websock.readyState === websock.CONNECTING) {
        // 若是 正在开启状态，则等待1s后重新调用
        setTimeout(function() {
            sendSock(agentData, callback)
        }, 1000)
    } else {
        // 若未开启 ，则等待1s后重新调用
        setTimeout(function() {
            sendSock(agentData, callback)
        }, 1000)
    }
}

function reconnection() {
    count = count + 1
    //console.log("reconnection...",count)
    // 1与服务器已经建立连接
    if (count >= MAX || websock.readyState === 1) {
        clearTimeout(t)
    } else {
        // 2已经关闭了与服务器的连接
        if (websock.readyState === 3) {
            initWebSocket()
        }
        //0正尝试与服务器建立连接,2正在关闭与服务器的连接
        t = setTimeout(function() { reconnection() }, 100)
        // t = setTimeout(function() {reconnection()}, 100)
    }
}
// 数据发送
function websocketsend(agentData) {
    websock.send(JSON.stringify(agentData))
}

function closeSocket() {
    console.log('closeSocket:', websock)
    isConnect = false
    if (websock) {
        websock.close()
        websock = null
    }
}

// 关闭
function websocketclose(e) {
    console.log('---websocketclose----', utils.getNowFormatDates('yyyy-MM-dd HH:mm:ss'))
    if (websock) {
        reconnection()
    }
}

function websocketOpen(e) {
    console.log('连接成功')
}

export { initWebSocket, closeSocket, sendSock }
